package cn.demomaster.quickpicturer.helper;

import static android.app.Activity.RESULT_OK;
import android.Manifest;
import android.app.Activity;
import android.content.ClipData;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.core.content.FileProvider;

import com.demomaster.quickcompat.util.QDFileUtil;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import cn.demomaster.quickpicturer.activity.CameraIDCardActivity;
import cn.demomaster.quickpicturer.activity.PictureSelectorActitity;
import cn.demomaster.quickpicturer.config.ImageActionRequest;
import cn.demomaster.quickpicturer.constants.ImageActionType;
import cn.demomaster.quickpicturer.model.ImageInfo;
import cn.demomaster.quickpicturer.util.FileProviderUtils;
import cn.demomaster.quickpicturer.util.PermissionUtil;

/**
 * 图片采集类
 *
 * @author squirrel桓
 * @date 2018/11/16.
 * description：
 */

public class PhotoHelper {
    private static final String TAG = "PhotoHelper";
    //String authority;//FileProvider
    private Map<Context, ImageActionRequest> requestMap;
    ActivityResultLauncher activityResultLauncher;
    ActivityResultCallback activityResultCallback = new ActivityResultCallback<Uri>() {
        @Override
        public void onActivityResult(Uri result) {
//                if(activityResultCallbackList.get(0)!=null){
//                    activityResultCallbackList.get(0).onSuccess(null,"");
//                    activityResultCallbackList.remove(0);
//                }
            onActivityResultImpForFragment(result);
        }
    };
    static PhotoHelper instance;

    public static PhotoHelper getInstance() {
        if (instance == null) {
            instance = new PhotoHelper();
        }
        return instance;
    }

    private PhotoHelper() {
        this.requestMap = new HashMap<>();
    }
//    public void init(String authority){
//        this.authority = authority;
//    }


    //    private PhotoHelper(Activity context, Fragment fragment, String authority) {
//        this.mActivity = context;
//        this.authority = authority;
//        if (fragment != null) {
//            this.mFragment = fragment;
//            activityResultLauncher = fragment.registerForActivityResult(new ActivityResultContracts.GetContent(), activityResultCallback);
//        }
//    }


    public void onRelease(Object self) {
        if (self instanceof Activity) {
            if (requestMap != null) {
                requestMap.remove(self);
            }
        }
    }

//    public void scanQrcode(OnTakePhotoResult onTakePhotoResult) {
//        Builder builder;
//        if (mFragment != null) {
//            builder = new Builder(mFragment);
//        } else {
//            builder = new Builder(mActivity);
//        }
//        builder.setRequestType(ImageSource.SCAN_QRCODE);
//        builder.onTakePhotoResult = onTakePhotoResult;
//        takePhoto2(builder);
//    }

    public void execute(ImageActionRequest builder) {
        //takePhoto2(builder);
        String[] requestPermissions = null;
        switch (builder.imageActionType) {
            case TAKE_PHOTO:
            case TAKE_PHOTO_CROP:
            case TAKE_PHOTO_FOR_ID_CARD:
                requestPermissions = permissions_camera;
                break;
            case SELECT_FROM_GALLERY:
            case SELECT_FROM_GALLERY_AND_CROP:
            case SELECT_FROM_CUSTOM_GALLERY:
            case SELECT_FROM_CUSTOM_GALLERY_AND_CROP:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
                    requestPermissions = permissions_gallery3;
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    requestPermissions = permissions_gallery2;
                } else {
                    requestPermissions = permissions_gallery;
                }
                break;
        }

        PermissionUtil.requestPermissions(builder.activity == null ? builder.fragment.getActivity() : builder.activity, requestPermissions, new PermissionUtil.PermissionResultCallback() {
            @Override
            public void onPermissionsGranted(String[] var1) {
                requestMap.put(builder.getActivity(), builder);
                performAction(builder);
            }

            @Override
            public void onPermissionsDenied() {
                Log.e(TAG, "onPermissionsDenied");
            }
        });
    }

    private void performAction(ImageActionRequest builder) {
        switch (builder.imageActionType) {
            case TAKE_PHOTO://拍照
            case TAKE_PHOTO_CROP://拍照截取
                takePhoto(builder);
                break;
            case CROP_IMAGE:
                cropPhotoImp(builder);
                break;
            case TAKE_PHOTO_FOR_ID_CARD://PHOTOHELPER_REQUEST_CODE_TAKE_PHOTO_FOR_IDCARD://拍身份证
                takePhotoForIDCardImp(builder);
                break;
            case SELECT_FROM_GALLERY:
            case SELECT_FROM_GALLERY_AND_CROP:// PHOTOHELPER_REQUEST_CODE_GALLERY://从相册选取照片
                selectPhotoFromGalleryImp(builder);
                break;
            case SCAN_QR_CODE:// PHOTOHELPER_REQUEST_CODE_SCAN_QRCODE://扫描二维码
                scanQrcodeImp(builder);
                break;
            case SELECT_FROM_CUSTOM_GALLERY:
            case SELECT_FROM_CUSTOM_GALLERY_AND_CROP://PHOTOHELPER_REQUEST_CODE_GALLERY2://从自定义图库选择
                startSimplePictureActivityImp(builder);
                break;
        }
    }

    /**
     * 调用相机拍照
     *
     * @param onTakePhotoResult
     * @param outUri            拍照保存的路径
     */
//    public void takePhoto(ImageConfig imageConfig, QuickPicturer.OnImageSelectedListener onTakePhotoResult) {
//        ImageRequest builder = new ImageRequest(imageConfig);
//        builder.setRequestType(ImageSource.CAMERA);
//        builder.setOnImageSelectedListener(onTakePhotoResult);
//        takePhoto2(builder);
//    }

    /**
     * 调用相机拍照并且裁剪
     *
     * @param onTakePhotoResult
     */
//    public void takePhotoCrop(ImageConfig imageConfig, QuickPicturer.OnImageSelectedListener onImageSelectedListener) {
//        ImageActionRequest builder = new ImageActionRequest(imageConfig);
//        builder.setOutputUri(imageConfig.outputUri);
//        builder.setEnableCrop(true);
//        builder.setRequestType(ImageSourceType.CAMERA);
//        builder.setOnImageSelectedListener(new QuickPicturer.OnImageSelectedListener() {
//            @Override
//            public void onImagesSelected(String[] images) {
//                builder.setSrcUri(imageConfig.outputUri);
//                builder.setOnImageSelectedListener(onImageSelectedListener);
//                photoCrop(builder);
//            }
//        });
//        takePhoto2(builder);
//    }

    /**
     * 图片截取
     */
//    public void photoCrop(ImageActionRequest builder) {
//        if (builder == null) {
//            return;
//        }
//        builder.setImageActionType(ImageActionType.TAKE_PHOTO_CROP);
//        takePhoto2(builder);
//    }

    /**
     * 调用图库获取图片
     *
     * @param onTakePhotoResult
     */
//    public void selectPhotoFromGallery(ImageConfig imageConfig,QuickPicturer.OnImageSelectedListener onTakePhotoResult) {
//        ImageActionRequest builder = new ImageActionRequest(imageConfig);
//        builder.setOnImageSelectedListener(onTakePhotoResult);
//        builder.setImageActionType(ImageActionType.SELECT_FROM_GALLERY);
//        takePhoto2(builder);
//    }

    /**
     * 调用自定义图库获取图片
     *
     * @param onSelectPictureResult
     */
//    public void selectPhotoFromMyGallery(ImageConfig config,QuickPicturer.OnImageSelectedListener onSelectPictureResult) {
//        ImageActionRequest imageActionRequest = new ImageActionRequest(config);
//        imageActionRequest.setRequestType(CUSTOM_GALLERY);
//        Log.d(TAG, "调用自定义图库获取图片,数量："+ imageActionRequest.maxImages);
//        imageActionRequest.setOnImageSelectedListener(onSelectPictureResult);
//        takePhoto2(imageActionRequest);
//    }

    /**
     * 调用相册并截取
     *
     * @param onTakePhotoResult
     */
//    public  void selectPhotoFromGalleryAndCrop(ImageConfig imageConfig, final QuickPicturer.OnImageSelectedListener onTakePhotoResult) {
//        ImageActionRequest builder = new ImageActionRequest(imageConfig);
//        builder.setRequestType(ImageSourceType.GALLERY);
//        builder.setOnImageSelectedListener(new QuickPicturer.OnImageSelectedListener() {
//            @Override
//            public void onImagesSelected(String[] images) {
////                Log.d(TAG, "onSuccess:" + data + "," + path);
////                if (data != null) {
////                    builder.setSrcUri(data.getData());
////                } else {
////                    builder.setSrcUri(Uri.parse(path));
////                }
//                builder.setOutputUri(imageConfig.outputUri);
//                builder.setOnImageSelectedListener(onTakePhotoResult);
//                photoCrop(builder);
//            }
//        });
//        takePhoto2(builder);
//    }

    /**
     * 拍摄身份证
     *
     * @param onTakePhotoResult
     */
//    public void takePhotoForIDCard(ImageConfig imageConfig,QuickPicturer.OnImageSelectedListener onTakePhotoResult) {
//        ImageActionRequest builder = new ImageActionRequest(imageConfig);
//        builder.setOnImageSelectedListener(onTakePhotoResult);
//        builder.setRequestType(ImageSourceType.CAMERA_FOR_ID_CARD);
//        takePhoto2(builder);
//    }

    String[] permissions_gallery = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};//android29及其以下使用文件权限校验
    String[] permissions_gallery2 = {Manifest.permission.READ_MEDIA_IMAGES};//android30使用读区媒体图片权限校验 {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
    String[] permissions_gallery3 = {Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED};
    String[] permissions_camera = {Manifest.permission.CAMERA};

    public void takePhoto(ImageActionRequest builder) {
        Uri fileUri = builder.outputUri;
        if (fileUri == null) {
            // 判断存储卡是否可以用，可用进行存储
            // if (StorageUtils.hasSdcard()) {
//            String savePath = Environment
//                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + mActivity.getPackageName() + "/photo";
//            File file = new File(savePath, System.currentTimeMillis() + ".jpg");
//            if (!file.exists()) {
//                QDFileUtil.createFile(file);
//            }
            File photoFile = null;
            try {
                if (builder.saveDirectory == null) {
                    // 创建一个临时文件来保存图片
                    photoFile = createImageFile(builder.getContext());
                } else {
                    photoFile = createImageFile(builder.getActivity(),builder.saveDirectory);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            String photoPath = photoFile.getAbsolutePath();
            Uri photoURI = FileProvider.getUriForFile(builder.getActivity(),
                    builder.authority,
                    photoFile);
            builder.setOutputUri(photoURI);
            builder.setOutputPath(photoPath);
            //            fileUri = QDFileUtil.getUrifromFile(builder.getContext(), builder.authority, photoFile);
//            builder.setOutputUri(fileUri);
            // builder.setOutputPath(photoFile.getAbsolutePath());
            //Log.d(TAG, "fileUri:" + fileUri);
        } else {
            File file = new File(fileUri.getPath());
            if (!file.exists()) {
                QDFileUtil.createFile(file);
            }
        }

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //if(!builder.enableCrop) {
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, builder.outputUri);//如果此处指定，返回值的data为null
        //}
        takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        if (builder.fragment != null) {
            //activityResultLauncher.launch("TODO");
            builder.fragment.getActivity().startActivityForResult(takePictureIntent, builder.requestCode);
        } else {
            builder.activity.startActivityForResult(takePictureIntent, builder.requestCode);
        }
    }

    private File createImageFile(Context context) throws IOException {
        // 在应用私有目录下创建文件
        File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        return createImageFile(context,storageDir);
    }

    private File createImageFile(Context context, File storageDir) throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        storageDir.mkdirs();
        Log.d(TAG, "storageDir:" + storageDir);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.DATA, image.getPath());
        context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        return image;
    }

    /**
     * 图片裁剪功能
     */
    private void cropPhotoImp(ImageActionRequest builder) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(builder.srcUri, "image/*");

        // 设置裁剪参数
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        intent.putExtra("aspectX", builder.aspectX);
        intent.putExtra("aspectY", builder.aspectY);
        intent.putExtra("outputX", builder.outputX);
        intent.putExtra("outputY", builder.outputY);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);

        // 根据API版本和是否存在outputUri来设置输出
        if (builder.outputUri != null) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, builder.outputUri);
        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
            // 对于Android 10及以下版本，不支持直接使用FileProvider
            // 通常需要创建一个临时文件，但这里我们假定不需要
            // intent.putExtra(MediaStore.EXTRA_OUTPUT, targetUri);
        } else {
            try {
                File photoFile = builder.saveDirectory != null ?
                        createImageFile(builder.getActivity(),builder.saveDirectory) :
                        createImageFile(builder.getContext());
                Uri fileUri = QDFileUtil.getUrifromFile(builder.getContext(), builder.authority, photoFile);
                builder.setOutputUri(fileUri);
                builder.setOutputPath(photoFile.getAbsolutePath());
                intent.putExtra(MediaStore.EXTRA_OUTPUT, builder.outputUri);
            } catch (IOException e) {
                throw new RuntimeException("Failed to create image file for cropping", e);
            }
        }

        // 设置返回数据的方式
        intent.putExtra("return-data", false);
        //设置授权
        FileProviderUtils.grantUriPermission(builder.getContext(), intent, builder.outputUri);
        // 设置临时权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {// && !isMIUI()) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }

        Log.d(TAG, "准备裁剪[" + builder.requestCode);
        requestMap.put(builder.getActivity(), builder);
        // 启动裁剪活动
        Activity activity = builder.fragment != null ? builder.fragment.getActivity() : builder.getActivity();
        activity.startActivityForResult(intent, builder.requestCode);
    }

    private void takePhotoForIDCardImp(ImageActionRequest builder) {
        Intent intent = new Intent(builder.getActivity(), CameraIDCardActivity.class);
        //intent.putExtra(PHOTOHELPER_RESULT_CODE, resultCodeTakePhoto);
        if (builder.fragment != null) {
            builder.fragment.getActivity().startActivityForResult(intent, builder.requestCode);
        } else {
            builder.activity.startActivityForResult(intent, builder.requestCode);
        }
    }

    private void selectPhotoFromGalleryImp(ImageActionRequest builder) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        intent.setType("image/*");
        if (builder.maxImages > 1) {
            // 允许用户选择多个图片
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, builder.maxImages > 1);
            // 设置张数限制
            //intent.putExtra(Intent.EXTRA_MAX_RESULTS, 5);
        }
        if (builder.fragment != null) {
            builder.fragment.getActivity().startActivityForResult(intent, builder.requestCode);
        } else {
            builder.getActivity().startActivityForResult(intent, builder.requestCode);
        }
    }

    private void scanQrcodeImp(ImageActionRequest builder) {
        Intent intent = new Intent(builder.getActivity(), builder.scanActivityClass);
        /*ZxingConfig是配置类  可以设置是否显示底部布局，闪光灯，相册，是否播放提示音  震动等动能
         * 也可以不传这个参数
         * 不传的话  默认都为默认不震动  其他都为true
         * */

        //ZxingConfig config = new ZxingConfig();
        //config.setShowbottomLayout(true);//底部布局（包括闪光灯和相册）
        //config.setPlayBeep(true);//是否播放提示音
        //config.setShake(true);//是否震动
        //config.setShowAlbum(true);//是否显示相册
        //config.setShowFlashLight(true);//是否显示闪光灯
        //intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
        if (builder.fragment != null) {
            builder.fragment.getActivity().startActivityForResult(intent, builder.requestCode);
        } else {
            builder.activity.startActivityForResult(intent, builder.requestCode);
        }
    }

    /**
     * 打开图片选择器页面
     */
    private void startSimplePictureActivityImp(ImageActionRequest builder) {
        Intent intent = new Intent(builder.getActivity(), PictureSelectorActitity.class);
        //intent.putExtra(PHOTOHELPER_RESULT_CODE, resultCodeTakePhoto);
        intent.putExtra("MaxCount", builder.maxImages);
        if (builder.fragment != null) {
            //activityResultLauncher.launch("TODO");
            builder.fragment.getActivity().startActivityForResult(intent, builder.requestCode);
        } else {
            builder.activity.startActivityForResult(intent, builder.requestCode);
        }
    }

    public final static String PHOTOHELPER_RESULT_PATH = "PHOTOHELPER_RESULT_PATH";
   // public final static String PHOTOHELPER_RESULT_PATHES = "PHOTOHELPER_RESULT_PATHES";

    public void onActivityResult(Context context, int requestCode, int resultCode, Intent data) {
        //onActivityResultImp(requestCode, resultCode, data);
        ImageActionRequest request = requestMap.get(context);
        if (request == null || request.requestCode != requestCode) {
            Log.e(TAG, "currentBuilder=" + request + "，onActivityResultImp: requestCode != currentBuilder.requestCode");
            return;
        }

        if (resultCode == RESULT_OK) {
            requestMap.remove(context);
            if (request.onImageSelectedListener != null) {
                switch (request.imageActionType) {
                    case TAKE_PHOTO:
                    case TAKE_PHOTO_CROP:
                        if (request.isCroppingEnabled) {//裁剪
                            request.setSrcUri(request.outputUri);
                            request.setImageActionType(ImageActionType.CROP_IMAGE);
                            request.resetRequestCode();
                            execute(request);
                            return;
                        }
                        Log.d(TAG, "拍照完成");
                        request.onImageSelectedListener.onImagesSelected(request.outputUri);
                        return;
                    case CROP_IMAGE:
                        Log.d(TAG, "裁剪完成[" + request.requestCode);
                        if (data != null && data.getData() != null) {
                            //Log.d(TAG, "裁剪完成1: "+QDFileUtil.uriToFile(context, data.getData()).getAbsolutePath());
                            request.onImageSelectedListener.onImagesSelected(data.getData());
                        } else {
                            //Log.d(TAG, "裁剪完成2: "+QDFileUtil.uriToFile(context,request.outputUri).getAbsolutePath());
                            request.onImageSelectedListener.onImagesSelected(request.outputUri);
                        }
                        return;
                    case TAKE_PHOTO_FOR_ID_CARD:
                    case SELECT_FROM_GALLERY:
                    case SELECT_FROM_GALLERY_AND_CROP:
                        if (data != null) {
                            Uri[] urisArray = null;
                            ClipData clipData = data.getClipData();
                            if (clipData != null) {//多选
                                int numSelected = clipData.getItemCount();
                                urisArray = new Uri[numSelected];
                                for (int i = 0; i < numSelected; i++) {
                                    urisArray[i] = clipData.getItemAt(i).getUri();
                                }
                            } else {//单选
                                Uri uri = data.getData();
                                urisArray = new Uri[]{uri};
                                // 如果用户只选择了单个图片，data.getData() 将包含单个 URI
                                if (request.isCroppingEnabled) {//裁剪
                                    //Uri imageUri = FileProvider.getUriForFile(this, request.authority, Conso);
                                    request.setSrcUri(uri);
                                    request.setImageActionType(ImageActionType.CROP_IMAGE);
                                    request.resetRequestCode();
                                    execute(request);
                                    return;
                                }
                            }
                            Log.d(TAG, "图片选择完成");
                            request.onImageSelectedListener.onImagesSelected(urisArray);
                        }
                        return;
                    case SELECT_FROM_CUSTOM_GALLERY:
                    case SELECT_FROM_CUSTOM_GALLERY_AND_CROP:
                        if (data != null) {
                            ArrayList<ImageInfo> images = data.getParcelableArrayListExtra("imagesInfos");
                            if (images != null) {
                                Uri[] urls = new Uri[images.size()];
                                for (int i = 0; i < images.size(); i++) {
                                    urls[i] = images.get(i).getUri();
                                }

                                if (urls.length == 1 && request.isCroppingEnabled) {//裁剪
                                    request.setSrcUri(urls[0]);
                                    request.setImageActionType(ImageActionType.CROP_IMAGE);
                                    request.resetRequestCode();
                                    execute(request);
                                    return;
                                }

                                Log.d(TAG, "图片选择完成[" + request.requestCode + "-" + images.size());
                                request.onImageSelectedListener.onImagesSelected(urls);
                            }
                            return;
                        }
                        break;
                }
            }
        }
    }

    private void onActivityResultImpForFragment(Uri result) {

    }


}
